﻿using System;
using System.Collections;
using System.Text;
using System.Net.Mail;
using System.Xml;
using System.Xml.Linq;
using System.Text.RegularExpressions;
using System.ComponentModel;
using System.IO;


//调用
/*
    Email email = new Email();
    Email.EnableSSL=true ; //使用SSL认证，默认为不使用
    email.mailSubject = "";//邮件主题
    email.mailBody = "";//邮件内容
    email.mailToArray = new string[] { "3***9030@hangyickpaper.cn" };//接收者邮件集合
    或 email.mailTo= 带分号或是带逗号隔开的字符串 basys<basys@hangyickpaper.cn>;HY005072<HY005072@hangyickpaper.cn>
    email.mailCcArray = new string[] { "******@hangyickpaper.cn" };//抄送者邮件集合
    或 email.mailCc= 带分号或是带逗号隔开的字符串 "basys<basys@hangyickpaper.cn>;HY005072<HY005072@hangyickpaper.cn>"
    email.mailBccArray = new string[] { "******@hangyickpaper.cn" };//密件抄送者邮件集合
    或 email.mailBcc= 带分号或是带逗号隔开的字符串 basys<basys@hangyickpaper.cn>;HY005072<HY005072@hangyickpaper.cn>
    email.Send();
*/


namespace CronCommon
{
    public class Email
    {
        private string mailto;
        private string mailcc;
        private string mailbcc;

        public Email()
        {
            this.isbodyHtml = true;
            this.EnableSSL = false;

            XDocument xd = XDocument.Load($"{Dir.GetCurrentDirectory()}\\config.xml");
            foreach (XElement item in xd.Root.Descendants("mail"))
            {
              if (item.Element("mailFrom")!=null)  this.mailFrom = item.Element("mailFrom").Value;
              if (item.Element("mailPwd") != null) this.mailPwd = item.Element("mailPwd").Value;
              if (item.Element("host") != null) this.host = item.Element("host").Value;
              if (item.Element("port") != null) this.port = Convert.ToInt32(item.Element("port").Value);
              if (item.Element("EnableSSL") != null) this.EnableSSL = Convert.ToBoolean(item.Element("EnableSSL").Value);
            }
            xd = null;
        }

        public Email(CronStruct cs):this()
        {
            this.mailSubject = cs.MailSubject;
            this.mailBody = cs.MailBody;
            this.mailTo = cs.MailTO;

            if (!string.IsNullOrWhiteSpace(cs.MailCC)) this.mailCc = cs.MailCC;
            if (!string.IsNullOrWhiteSpace(cs.MailBCC)) this.mailBcc = cs.MailBCC;

            if (File.Exists(cs.attachMentFilename))
                this.attachmentsPath = new string[] { cs.attachMentFilename };
        }

        /// <summary>
        /// 邮件发送人
        /// </summary>
        public string mailFrom { get; set; }

        public string[] mailToArray { get; set; }

        /// <summary>
        /// 邮件接收人
        /// </summary>
        public string mailTo
        {
            get { return mailto; }
            set
            {
                this.mailToArray = value.Replace(',', ';').Split(';');
                this.mailto = value;
            }
        }

        public string[] mailCcArray { get; set; }

        public string mailCc
        {
            get { return mailcc; }
            set
            {
                this.mailCcArray = value.Replace(',', ';').Split(';');
                this.mailcc = value;
            }

        }

        public string[] mailBccArray { get; set; }

        public string mailBcc
        {
            get { return mailbcc; }
            set
            {
                this.mailBccArray = value.Replace(',', ';').Split(';');
                this.mailbcc = value;
            }

        }

        public string mailSubject { get; set; }

        public string mailBody { get; set; }

        public string mailPwd { get; set; }

        public string host { get; set; }
        public int port { get; set; }

        /// 正文是否是html格式
        public bool isbodyHtml { get; set; }

        //是否使用SSL验证
        public bool EnableSSL { get; set; }

        /// 附件
        public string[] attachmentsPath { get; set; }

        public bool Send()
        {
            //使用指定的邮件地址初始化MailAddress实例
            MailAddress maddr = new MailAddress(mailFrom);
            //初始化MailMessage实例
            MailMessage myMail = new MailMessage();


            //向收件人地址集合添加邮件地址
            if (mailToArray != null)
            {
                for (int i = 0; i < mailToArray.Length; i++)
                {
                    if (!string.IsNullOrWhiteSpace(mailToArray[i].ToString()))
                        myMail.To.Add(mailToArray[i].ToString());
                }
            }


            //向抄送收件人地址集合添加邮件地址
            if (mailCcArray != null)
            {
                for (int i = 0; i < mailCcArray.Length; i++)
                {
                    if (!string.IsNullOrWhiteSpace(mailCcArray[i].ToString())) 
                        myMail.CC.Add(mailCcArray[i].ToString());
                }
            }


            //密件抄向抄送收件人地址集合添加邮件地址
            if (mailBccArray != null)
            {
                for (int i = 0; i < mailBccArray.Length; i++)
                {
                    if (!string.IsNullOrWhiteSpace(mailBccArray[i].ToString())) 
                        myMail.Bcc.Add(mailBccArray[i].ToString());
                }
            }

            //发件人地址
            myMail.From = maddr;

            //电子邮件的标题
            myMail.Subject = mailSubject;

            //电子邮件的主题内容使用的编码
            myMail.SubjectEncoding = Encoding.UTF8;

            //电子邮件正文
            myMail.Body = mailBody;

            //电子邮件正文的编码
            myMail.BodyEncoding = Encoding.UTF8;

            myMail.Priority = MailPriority.Normal;

            myMail.IsBodyHtml = isbodyHtml;

            //在有附件的情况下添加附件
            try
            {
                if (attachmentsPath != null && attachmentsPath.Length > 0)
                {
                    Attachment attachFile = null;
                    foreach (string path in attachmentsPath)
                    {
                        attachFile = new Attachment(path);
                        myMail.Attachments.Add(attachFile);
                    }
                }
            }
            catch (Exception err)
            {
                Log.Writter(string.Format("[{0}]在添加附件时有错误{1}", err.Message, DateTime.Now.ToString()));
            }


           SmtpClient smtp = new SmtpClient();
           try
            {
                //是否使用SSL认证              
                if (this.EnableSSL == true)
                {
                    smtp.EnableSsl = this.EnableSSL;
                    smtp.UseDefaultCredentials = false;
                    smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
                    smtp.Timeout = 300000;
                    Log.Writter(string.Format("[使用SSL认证:{0}]", smtp.EnableSsl.ToString()));
                }
                //设置SMTP邮件服务器
                smtp.Host = host;
                smtp.Port = port;

                Log.Writter(string.Format("[host:{0}]",smtp.Host));
                Log.Writter(string.Format("[port:{0}]",smtp.Port));
                


                string SendMailUser;

                SendMailUser = mailFrom;

                if (mailFrom.IndexOf("<") > 0)
                {
                    SendMailUser = mailFrom.Substring(mailFrom.IndexOf("<") + 1).Replace(">", "").Trim();
                }

                //指定发件人的邮件地址和密码以验证发件人身份
                smtp.Credentials = new System.Net.NetworkCredential(mailFrom, mailPwd);

                Log.Writter($"接收人:{this.mailTo}");
                Log.Writter($"抄送人:{this.mailcc}");
                Log.Writter($"密件抄送:{this.mailbcc}");
                Log.Writter($"邮件主旨:{this.mailSubject}");
                Log.Writter($"邮件内容:{this.mailBody}");
                Log.Writter($"[登录用户名:[{mailFrom}]");
                Log.Writter($"[登录超时时间:{smtp.Timeout.ToString()}]");

                //将邮件发送到SMTP邮件服务器
                smtp.Send(myMail);
                return true;

            }
            catch (System.Net.Mail.SmtpException ex)
            {                
                Log.Writter(string.Format("[{0}]", ex.Message));
                return false;
            }
            finally {
                smtp.Dispose();
            }


        }
    }

}

